package com.changgou.seckill.service.impl;

import com.alibaba.fastjson.JSON;
import com.changgou.seckill.config.SeckillConfirmCallback;
import com.changgou.seckill.config.RabbitMQConfig;
import com.changgou.seckill.dao.SeckillOrderMapper;
import com.changgou.seckill.pojo.SeckillGoods;
import com.changgou.seckill.pojo.SeckillOrder;
import com.changgou.seckill.service.SeckillOrderService;
import com.changgou.seckill.task.SeckillGoodsPushTask;
import com.changgou.util.IdWorker;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * @Author: HuangFu
 * @Date: 2020/2/23 16:15
 * @Description: 秒杀订单服务
 */
@Service
public class SeckillOderServiceImpl implements SeckillOrderService {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private IdWorker idWorker;
    @Autowired
    private SeckillOrderMapper seckillOrderMapper;
    @Autowired
    private SeckillConfirmCallback seckillConfirmCallback;

    /**
     * 订单秒杀
     * @param username
     * @param id
     * @param time
     * @return
     */
    @Override
    public boolean add(String username, Long id, String time) {
        //防止恶意下单
        boolean result = this.preventRepeatCommit(username, id);
        if(result){
            return false;
        }

        //校验是否已经购买,防止相同商品重复秒杀
        SeckillOrder seckillOrder = seckillOrderMapper.getOrderInfoByUserNameAndGoodsId(username, id);
        if(seckillOrder != null){
            return false;
        }

        //获取redis中秒杀商品数据
        SeckillGoods seckillGoods = (SeckillGoods) redisTemplate.boundHashOps(SeckillGoodsPushTask.SECKILL_GOODS_KEY + time).get(id);
        //获取redis库存苏军
        String stackCount = (String) redisTemplate.boundValueOps(SeckillGoodsPushTask.SECKILL_GOODS_STOCK_COUNT_KEY + id).get();

        //商品库存数据是否存在
        if(seckillGoods == null || StringUtils.isEmpty(stackCount) || Integer.valueOf(stackCount)<=0){
            return false;
        }

        //redis库存删减，原子性操作防止并发超卖问题
        Long decrement = redisTemplate.boundValueOps(SeckillGoodsPushTask.SECKILL_GOODS_STOCK_COUNT_KEY + id).decrement(1);
        //小于等于0时，清空redis中的商品数据
        if(decrement<=0){
            //删除商品
            redisTemplate.boundHashOps(SeckillGoodsPushTask.SECKILL_GOODS_KEY + time).delete(id);
            //删除库存
            redisTemplate.delete(SeckillGoodsPushTask.SECKILL_GOODS_STOCK_COUNT_KEY + id);
        }

        //插入秒杀订单
        seckillOrder = new SeckillOrder();
        seckillOrder.setId(idWorker.nextId());
        seckillOrder.setSeckillId(id);
        seckillOrder.setMoney(seckillGoods.getCostPrice());
        seckillOrder.setUserId(username);
        seckillOrder.setSellerId(seckillGoods.getSellerId());
        seckillOrder.setCreateTime(new Date());
        seckillOrder.setStatus("0");

        //消息发送
        seckillConfirmCallback.sendMessage("", RabbitMQConfig.SECKILL_ORDER_KEY, JSON.toJSONString(seckillOrder));

        return true;
    }

    /**
     * 设置重复提交
     * @param username
     * @param id
     * @return
     */
    private boolean preventRepeatCommit(String username,Long id){
        String redis_key = "seckill_user_"+username+"_id_"+id;
        Long count = redisTemplate.boundValueOps(redis_key).increment(1);
        //count == 1 时为第一次提交，并设置key的有效期 5分钟
        if(count == 1){
            redisTemplate.expire(redis_key,5, TimeUnit.MINUTES);
            return false;
        }
//        if(count > 1){
//            return false;
//        }
        return true;
    }

}
